//
//  HistoryRecord.swift
//  ScarnKing
//
//  Created by ninebot on 2025/7/22.
//

import Foundation
import UIKit

// MARK: - History Record Type
enum HistoryRecordType: String, CaseIterable, Codable {
    case ocr = "OCR识别"
    case documentScan = "文档扫描"
    case translation = "AI翻译"
    case arDistance = "AR测距"
    case photoRestoration = "老照片修复"
    
    var icon: String {
        switch self {
        case .ocr:
            return "doc.text"
        case .documentScan:
            return "doc.viewfinder"
        case .translation:
            return "character.bubble"
        case .arDistance:
            return "ruler"
        case .photoRestoration:
            return "photo.artframe"
        }
    }
    
    var color: UIColor {
        switch self {
        case .ocr:
            return .systemBlue
        case .documentScan:
            return .systemGreen
        case .translation:
            return .systemPurple
        case .arDistance:
            return .systemOrange
        case .photoRestoration:
            return .systemPink
        }
    }
}

// MARK: - History Record
struct HistoryRecord: Codable {
    let id: String
    let type: HistoryRecordType
    let title: String
    let content: String
    let imageData: Data?
    let createdAt: Date
    let filePath: String?
    
    var formattedDate: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM-dd HH:mm"
        return formatter.string(from: createdAt)
    }
    
    init(type: HistoryRecordType, title: String, content: String, imageData: Data? = nil, filePath: String? = nil) {
        self.id = UUID().uuidString
        self.type = type
        self.title = title
        self.content = content
        self.imageData = imageData
        self.createdAt = Date()
        self.filePath = filePath
    }
}

// MARK: - History Record Manager
class HistoryRecordManager {
    static let shared = HistoryRecordManager()
    
    private let userDefaults = UserDefaults.standard
    private let historyKey = "HistoryRecords"
    private let maxRecords = 100
    
    private init() {}
    
    // MARK: - Public Methods
    func addOCRRecord(content: String, image: UIImage) {
        let imageData = image.jpegData(compressionQuality: 0.8)
        let record = HistoryRecord(
            type: .ocr,
            title: "OCR识别结果",
            content: content,
            imageData: imageData
        )
        addRecord(record)
    }
    
    func addDocumentScanRecord(image: UIImage) {
        let imageData = image.jpegData(compressionQuality: 0.8)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        let timeString = formatter.string(from: Date())
        
        let record = HistoryRecord(
            type: .documentScan,
            title: "文档扫描",
            content: "扫描时间：\(timeString)",
            imageData: imageData
        )
        addRecord(record)
    }
    
    func addTranslationRecord(originalText: String, translatedText: String, fromLanguage: String, toLanguage: String) {
        let record = HistoryRecord(
            type: .translation,
            title: "AI翻译",
            content: "从 \(fromLanguage) 翻译到 \(toLanguage)\n原文：\(originalText)\n译文：\(translatedText)"
        )
        addRecord(record)
    }
    
    func addARDistanceRecord(distance: String) {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        let timeString = formatter.string(from: Date())
        
        let record = HistoryRecord(
            type: .arDistance,
            title: "AR测距",
            content: "测量时间：\(timeString)\n距离：\(distance)"
        )
        addRecord(record)
    }
    
    func addPhotoRestorationRecord(originalImage: UIImage, restoredImage: UIImage) {
        let imageData = restoredImage.jpegData(compressionQuality: 0.8)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        let timeString = formatter.string(from: Date())
        
        let record = HistoryRecord(
            type: .photoRestoration,
            title: "老照片修复",
            content: "修复时间：\(timeString)",
            imageData: imageData
        )
        addRecord(record)
    }
    
    func getAllRecords() -> [HistoryRecord] {
        guard let data = userDefaults.data(forKey: historyKey),
              let records = try? JSONDecoder().decode([HistoryRecord].self, from: data) else {
            return []
        }
        return records.sorted { $0.createdAt > $1.createdAt }
    }
    
    func getRecords(of type: HistoryRecordType) -> [HistoryRecord] {
        return getAllRecords().filter { $0.type == type }
    }
    
    func deleteRecord(withId id: String) {
        var records = getAllRecords()
        records.removeAll { $0.id == id }
        saveRecords(records)
    }
    
    func clearAllRecords() {
        userDefaults.removeObject(forKey: historyKey)
    }
    
    // MARK: - Private Methods
    private func addRecord(_ record: HistoryRecord) {
        var records = getAllRecords()
        records.insert(record, at: 0)
        
        // 限制记录数量
        if records.count > maxRecords {
            records = Array(records.prefix(maxRecords))
        }
        
        saveRecords(records)
    }
    
    private func saveRecords(_ records: [HistoryRecord]) {
        if let data = try? JSONEncoder().encode(records) {
            userDefaults.set(data, forKey: historyKey)
        }
    }
} 